// 配置蓝心AI API
const BLUE_HEART_API = {
  endpoint: "https://api.vivo.com.cn/blueheart/chat", // 替换为实际API端点
  apiKey: "your-api-key-here", // 替换为你的API密钥
  model: "blueheart-pro" // 使用的模型名称
};

// 显示消息函数（保持不变）
function displayMessage(text, sender) {
  const messagesContainer = document.getElementById('chat-messages');
  const messageElement = document.createElement('div');
  messageElement.classList.add('message', `${sender}-message`);
  messageElement.textContent = text;
  messagesContainer.appendChild(messageElement);
  messagesContainer.scrollTop = messagesContainer.scrollHeight;
}

// 使用fetch API连接蓝心AI
async function queryBlueHeartAI(prompt) {
  try {
    const response = await fetch(BLUE_HEART_API.endpoint, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${BLUE_HEART_API.apiKey}`
      },
      body: JSON.stringify({
        model: BLUE_HEART_API.model,
        messages: [
          {
            role: "user",
            content: prompt
          }
        ],
        temperature: 0.7,
        max_tokens: 500
      })
    });

    if (!response.ok) {
      throw new Error(`API请求失败: ${response.status}`);
    }

    const data = await response.json();
    return data.choices[0].message.content;
  } catch (error) {
    console.error("调用蓝心AI失败:", error);
    return "抱歉，暂时无法连接到AI服务，请稍后再试。";
  }
}

// 使用axios连接蓝心AI（替代方案）
async function queryBlueHeartAIWithAxios(prompt) {
  try {
    const response = await axios.post(
      BLUE_HEART_API.endpoint,
      {
        model: BLUE_HEART_API.model,
        messages: [
          {
            role: "user",
            content: prompt
          }
        ],
        temperature: 0.7,
        max_tokens: 500
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${BLUE_HEART_API.apiKey}`
        }
      }
    );

    return response.data.choices[0].message.content;
  } catch (error) {
    console.error("调用蓝心AI失败:", error);
    return "抱歉，暂时无法连接到AI服务，请稍后再试。";
  }
}

// 修改后的processQuestion函数
async function processQuestion(question) {
  // 首先检查是否有预定义的简单回答
  const lowerQuestion = question.toLowerCase();
  
  const predefinedAnswers = {
    "你好": "您好！我是基于vivo蓝心AI的网页小助手，有什么可以帮您的吗？",
    "谢谢": "不客气，很高兴能帮到您！如果还有其他问题随时问我哦！",
    "默认": "正在查询蓝心AI..." // 默认回答改为加载状态
  };
  
  for (const [key, value] of Object.entries(predefinedAnswers)) {
    if (lowerQuestion.includes(key.toLowerCase())) {
      return value;
    }
  }
  
  // 复杂问题调用蓝心AI API
  return await queryBlueHeartAI(question);
}

// 初始化小助手（修改版）
async function initAssistant() {
  const toggleBtn = document.getElementById('assistant-toggle');
  const chatWindow = document.getElementById('assistant-chat');
  const sendBtn = document.getElementById('send-btn');
  const userInput = document.getElementById('user-input');
  
  // 切换聊天窗口显示/隐藏
  toggleBtn.addEventListener('click', () => {
    chatWindow.classList.toggle('hidden');
  });
  
  // 发送消息
  async function sendMessage() {
    const question = userInput.value.trim();
    if (question) {
      displayMessage(question, 'user');
      userInput.value = '';
      
      // 显示"正在思考"消息
      const thinkingMsg = displayMessage("正在思考...", 'assistant');
      
      try {
        const answer = await processQuestion(question);
        
        // 移除"正在思考"消息，显示真实回答
        document.getElementById('chat-messages').removeChild(thinkingMsg);
        displayMessage(answer, 'assistant');
      } catch (error) {
        document.getElementById('chat-messages').removeChild(thinkingMsg);
        displayMessage("处理请求时出错，请稍后再试。", 'assistant');
        console.error("处理消息出错:", error);
      }
    }
  }
  
  // 点击发送按钮
  sendBtn.addEventListener('click', sendMessage);
  
  // 按Enter键发送
  userInput.addEventListener('keypress', (e) => {
    if (e.key === 'Enter') {
      sendMessage();
    }
  });
  
  // 初始欢迎消息
  setTimeout(() => {
    displayMessage("您好！我是基于vivo蓝心AI的智能助手，有什么可以帮您的吗？", 'assistant');
  }, 1000);
}

// 当DOM加载完成后初始化
document.addEventListener('DOMContentLoaded', initAssistant);